import json
import os.path

class TCompManager:
    def __init__(self):
        self.defaultSettingsCodee="default"
        self.rootPath =""
        self.settings = {}
        self.components ={}
        self.componentTypes={}
        self.enableClientIps =[]
    def log (self , logData , sender=None):
        print( "logData" , logData , "" if sender==None else sender)
    def registComponentType(self , compTypeCode , compType , defaultSettings={}):
        try:
            self.componentTypes[compTypeCode] = {
                "code" : compTypeCode ,
                "type" : compType ,
                "defaultSettings" : defaultSettings
            }
        except Exception as er:
            self.manager.log(er , self)
    def loadComponents(self , settingsCode):
        try:
            dirName = os.path.dirname(os.path.dirname(__file__))
            self.rootPath = dirName
            settingsDirName ="/devhhinfoDatas"
            sfn = f"{settingsDirName}/apisettings/{settingsCode}.json"
            if not os.path.exists(sfn):
                sfn = f"{settingsDirName}/apisettings/{self.defaultSettingsCodee}.json"
            if os.path.exists(sfn):
                with open( sfn , 'r' , encoding='utf-8') as f :
                    try:
                        self.settings = json.loads(f.read())
                    except Exception as erSe:
                        self.log(erSe)
                for compTypeCode in self.settings['components']:
                    if compTypeCode in self.componentTypes.keys():
                        compType = self.componentTypes[compTypeCode]
                        for compCode in self.settings['components'][compTypeCode].keys():
                            compSettings = self.settings['components'][compTypeCode][compCode]
                            self.loadComp( compType , compCode , compSettings ,True)

            self.loadEnableClientIps()
        except Exception as er:
            self.log(er)
    def loadEnableClientIps( self  ):
        try:
            ips =[]
            whiteListPath = os.path.join( '/datas/tsEqu')
            if not os.path.exists(whiteListPath):
                os.makedirs(whiteListPath , 0x777)
            fn = os.path.join(whiteListPath , "whiteList.json")
            if os.path.exists(fn):
                with open(fn , 'r', encoding='utf-8') as f :
                    try:
                        content = f.read()
                        ips = json.loads(content)
                    except Exception as eer:
                        self.manager.log(eer)
            else:
                with open(fn , 'w' , encoding='utf-8') as f:
                    f.write('[]')
            self.enableClientIps =ips
        except Exception as er:
            self.log(er)
    def loadComp( self ,compType , compCode , compSettings , reloadFlag = False ):
        res = None
        try:
            if compCode in self.components.keys() and not  reloadFlag:
                res = self.components[compCode]
            else:
                comp:TComp = compType['type']()
                comp.manager = self
                comp.code = compCode
                comp.compSettings = compSettings
                comp.compInit()
                for task in comp.autoStartServices:
                    task()
                self.components[compCode] = comp
                res = comp
        except Exception as er:
            self.log(er)
        return  res
    def getComp(self , compCode):
        return None if  compCode not in self.components.keys() else self.components[compCode]
    def checkClient(self, clientIp):
        res = 0
        try:
            checkFlag = clientIp!=None and 'checkClient' in self.settings['server'] and   self.settings['server']['checkClient']>0
            if checkFlag :
                if clientIp in self.enableClientIps:
                    res = 1
            else:
                res = 1
        except Exception as er:
            self.log(er)
        return  res
compManager = TCompManager()

class TComp:
    def __init__(self ):
        self.manager = compManager
        self.code = ""
        self.compSettings={}
        self.componentTypes ={}
        self.handlers={}
        self.asyncHandlerKeys=[]
        self.autoStartServices ={}
    def compInit(self):
        try:
            pass
        except Exception as eer:
            self.manager.log(eer)
    def action(self , acCode , acParams):
        res = {}
        try:
            if acCode in self.handlers.keys():
                handler = self.handlers[acCode]
                res = handler(**acParams)
        except Exception as er:
            self.manager.log(er , self)
        return  res
    async def startSevices(self , acCode , acParams):
        res = {}
        try:
            for service in self.autoStartServices.values():
                service()
        except Exception as er:
            self.manager.log(er , self)
        return  res
